package cn.phonevane.dao.impl;



import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;

import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;



import cn.phonevane.dao.BaseDao;

public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao{
	
	public static Logger logger=Logger.getLogger(BaseDaoImpl.class);
	
	/**
	 * @param  theClass,id
	 * @return object 
	 */
	public Object load(Class entityClass, Long id) {
		Object object=null;
		try{
			object=getHibernateTemplate().load(entityClass, id);
			logger.info("load successful!");
			return object;
		}catch(DataAccessException e){
			logger.info("load failed!",e);
			
		}
		return object;
	}
	
	/**
	 * @param  hql
	 * @return list 
	 */
	public List find(String hql){
		List list=null;
		try{
			list=getHibernateTemplate().find(hql);
			logger.info("find successful!");
			return list;
		}catch(DataAccessException e){
			logger.info("find failed!",e);
		}
		return list;
	}
	
	/**
	 * @param  hql
	 * @return 任意集合
	 */
	public List<T> findByAll(String hql){
		List<T> list=null;
		try{
			list=getHibernateTemplate().find(hql);
			logger.info("find successful!");
			return list;
		}catch(DataAccessException e){
			logger.info("find failed!",e);
		}
		return list;
		
	}
	
	/**
	 * 使用 hql 语句进行操作
	 * 
	 * @param hql
	 *            HSQL 查询语句（使用回调函数访问外部变量，必须是final的）
	 * @param first
	 *            开始取数据的下标
	 * @param count
	 *            读取数据记录数
	 * @return  集合
	 */
	public List find(final String hql,final int first,final int count) {
		
		List list = getHibernateTemplate().executeFind(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				query.setFirstResult(first);
				query.setMaxResults(count);
				List list = query.list();
				logger.info("query successful!");
				return list;

			}
		});
		return list;
	}
	
	/**
	 * @param object
	 * @return boolean
	 */
	public boolean save(Object object) {
		try{
		getHibernateTemplate().save(object);
		logger.info("save successful!");
		return true;
		}catch(DataAccessException e){
			logger.info("save failed!",e);
		}
		return false;
	}

	

	

	

}
